import Toast from 'tdesign-miniprogram/toast/index';

import {
  cdnBase
} from '../../../config/index';

const imgPrefix = `${cdnBase}/`;

const recLeftImg = `${imgPrefix}common/rec-left.png`;
const recRightImg = `${imgPrefix}common/rec-right.png`;
const obj2Params = (obj = {}, encode = false) => {
  const result = [];
  Object.keys(obj).forEach((key) =>
    result.push(`${key}=${encode ? encodeURIComponent(obj[key]) : obj[key]}`),
  );

  return result.join('&');
};

// const basePage = require('../../common/BasePage')
const basePage = require('../../../common/BasePage')
Page({
  behaviors: [basePage],
  data: {
    /**当前门店 */
    storeSid: '',
    /**商品价格 */
    price: 0,
    // /**附近门店 */
    // storeArr: [],
    // showStore: false,

    isShowPromotionPop: false,
    activityList: [],
    recLeftImg,
    recRightImg,
    details: {},
    goodsTabArray: [{
        name: '商品',
        value: '', // 空字符串代表置顶
      },
      {
        name: '详情',
        value: 'goods-page',
      },
    ],
    storeLogo: `${imgPrefix}common/store-logo.png`,
    storeName: '云mall标准版旗舰店',
    jumpArray: [],
    // jumpArray: [{
    //     title: '首页',
    //     url: '/pages/home/home',
    //     iconName: 'home',
    //   },
    //   {
    //     title: '购物车',
    //     url: '/pages/cart/index',
    //     iconName: 'cart',
    //     showCartNum: true,
    //   },
    // ],
    isStock: true,
    cartNum: 0,
    soldout: false,
    buttonType: 1,
    buyNum: 1,
    selectedAttrStr: '',
    skuArray: [],
    primaryImage: '',
    specImg: '',
    isSpuSelectPopupShow: false,
    isAllSelectedSku: false,
    buyType: 0,
    outOperateStatus: false, // 是否外层加入购物车
    operateType: 0,
    selectSkuSellsPrice: 0,
    maxLinePrice: 0,

    maxSalePrice: 0,
    list: [],
    spuId: '',
    navigation: {
      type: 'fraction'
    },
    current: 0,
    autoplay: true,
    duration: 500,
    interval: 5000,
    soldNum: 0, // 已售数量
    /**请求中 */
    reqing: false,
  },

  handlePopupHide() {
    this.setData({
      isSpuSelectPopupShow: false,
    });
  },

  showSkuSelectPopup(type) {
    this.setData({
      buyType: type || 0,
      outOperateStatus: type >= 1,
      isSpuSelectPopupShow: true,
    });
  },

  buyItNow() {

    if (this.data.storeSid) {
      return this.preorder(this.data.storeSid);
    }
    let that = this;
    wx.showLoading({
      title: '获取定位...',
      mask: true,
    })
    wx.getLocation({
      altitude: true,
      highAccuracyExpireTime: 0,
      isHighAccuracy: true,
      type: "gcj02",
      success(res) {
        getApp().globalData.latitude = res.latitude;
        getApp().globalData.longitude = res.longitude;
        setTimeout(() => {
          that.request({
            url: that.data.host + '/v1/carts/store/' + that.data.details.sid,
            data: {
              latitude: res.latitude,
              longitude: res.longitude,

            },
            loadingTip: '获取门店'
          }, res => {
            // console.log('nearby-store', res);
            that.data.storeSid = res.data;
            that.preorder(res.data);
          })
        }, 100);
      },
      fail: (err) => {
        console.log('getLocation err', err);
        wx.showToast({
          title: '获取当前位置失败',
          icon: 'none',
        })
      },
      complete: () => {
        wx.hideLoading({
          noConflict: true,
        })
      }
    })

  },
  preorder(storeSid) {

    this.request({
      url: this.data.host + '/v1/goods/preorder',
      data: {
        goodsSid: this.data.details.sid,
        storeSid: storeSid,
        number: this.data.buyNum || 1
      },
      loadingTip: '预定...',
      method: 'post'
    }, res => {
      console.log('预定', res);
      setTimeout(() => {
        wx.showToast({
          title: '预定成功',
        })
      }, 100);

      wx.redirectTo({
        url: '/pages/order/list',
      })
    })
  },
  add_cart(storeSid) {
    this.request({
      url: this.data.host + '/v1/carts/add',
      data: {
        goodsSid: this.data.details.sid,
        storeSid: storeSid
      },
      method: 'put',
      loadingTip: '加购...'
    }, res => {

      setTimeout(() => {
        wx.showToast({
          title: '加购成功',

          icon: 'success',

        })
      }, 100);


    })
  },
  toAddCart() {
    // this.showSkuSelectPopup(2);
    // // console.log('toAddCart');
    if (this.data.storeSid) {
      return this.add_cart(this.data.storeSid)
    }
    let that = this;
    wx.showLoading({
      title: '获取定位...',
      mask: true,
    })
    wx.getLocation({
      altitude: true,
      highAccuracyExpireTime: 0,
      isHighAccuracy: true,
      type: "gcj02",
      success(res) {
        getApp().globalData.latitude = res.latitude;
        getApp().globalData.longitude = res.longitude;
        setTimeout(() => {
          that.request({
            url: that.data.host + '/v1/carts/store/' + that.data.details.sid,
            data: {
              latitude: res.latitude,
              longitude: res.longitude,
              // goodsSid: that.data.details.sid
            },
            loadingTip: '获取门店'
          }, res => {
            // console.log('nearby-store', res);
            that.data.storeSid = res.data;
            that.add_cart(res.data)
          })
        }, 100);
      },
      fail: (err) => {
        console.log('getLocation err', err);
        wx.showToast({
          title: '获取当前位置失败',

          icon: 'none',

        })
      },
      complete: () => {
        wx.hideLoading({
          noConflict: true,
        })
      }

    })
  },
  onVisibleChange(e) {
    this.setData({
      showStore: e.detail.visible,
    });
  },


  showCurImg(e) {
    const {
      index
    } = e.detail;
    const {
      images
    } = this.data.details;
    wx.previewImage({
      current: images[index],
      urls: images, // 需要预览的图片http链接列表
    });
  },

  onPageScroll({
    scrollTop
  }) {
    const goodsTab = this.selectComponent('#goodsTab');
    goodsTab && goodsTab.onScroll(scrollTop);
  },

  chooseSpecItem(e) {
    const {
      specList
    } = this.data.details;
    const {
      selectedSku,
      isAllSelectedSku
    } = e.detail;
    if (!isAllSelectedSku) {
      this.setData({
        selectSkuSellsPrice: 0,
      });
    }
    this.setData({
      isAllSelectedSku,
    });
    this.getSkuItem(specList, selectedSku);
  },

  getSkuItem(specList, selectedSku) {
    const {
      skuArray,
      primaryImage
    } = this.data;
    const selectedSkuValues = this.getSelectedSkuValues(specList, selectedSku);
    let selectedAttrStr = ` 件  `;
    selectedSkuValues.forEach((item) => {
      selectedAttrStr += `，${item.specValue}  `;
    });
    // eslint-disable-next-line array-callback-return
    const skuItem = skuArray.filter((item) => {
      let status = true;
      (item.specInfo || []).forEach((subItem) => {
        if (
          !selectedSku[subItem.specId] ||
          selectedSku[subItem.specId] !== subItem.specValueId
        ) {
          status = false;
        }
      });
      if (status) return item;
    });
    this.selectSpecsName(selectedSkuValues.length > 0 ? selectedAttrStr : '');
    if (skuItem) {
      this.setData({
        selectItem: skuItem,
        selectSkuSellsPrice: skuItem.price || 0,
      });
    } else {
      this.setData({
        selectItem: null,
        selectSkuSellsPrice: 0,
      });
    }
    this.setData({
      specImg: skuItem && skuItem.skuImage ? skuItem.skuImage : primaryImage,
    });
  },

  // 获取已选择的sku名称
  getSelectedSkuValues(skuTree, selectedSku) {
    const normalizedTree = this.normalizeSkuTree(skuTree);
    return Object.keys(selectedSku).reduce((selectedValues, skuKeyStr) => {
      const skuValues = normalizedTree[skuKeyStr];
      const skuValueId = selectedSku[skuKeyStr];
      if (skuValueId !== '') {
        const skuValue = skuValues.filter((value) => {
          return value.specValueId === skuValueId;
        })[0];
        skuValue && selectedValues.push(skuValue);
      }
      return selectedValues;
    }, []);
  },

  normalizeSkuTree(skuTree) {
    const normalizedTree = {};
    skuTree.forEach((treeItem) => {
      normalizedTree[treeItem.specId] = treeItem.specValueList;
    });
    return normalizedTree;
  },

  selectSpecsName(selectSpecsName) {
    if (selectSpecsName) {
      this.setData({
        selectedAttrStr: selectSpecsName,
      });
    } else {
      this.setData({
        selectedAttrStr: '',
      });
    }
  },

  addCart() {
    const {
      isAllSelectedSku
    } = this.data;
    Toast({
      context: this,
      selector: '#t-toast',
      message: isAllSelectedSku ? '点击加入收藏' : '请选择规格',
      icon: '',
      duration: 1000,
    });
  },

  gotoBuy(type) {
    const {
      isAllSelectedSku,
      buyNum
    } = this.data;
    console.log('gotoBuy', buyNum);
    if (!isAllSelectedSku) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请选择规格',
        icon: '',
        duration: 1000,
      });
      return;
    }
    this.handlePopupHide();
    const query = {
      quantity: buyNum,
      storeId: '1',
      spuId: this.data.spuId,
      goodsName: this.data.details.title,
      skuId: type === 1 ? this.data.skuList[0].skuId : this.data.selectItem.skuId,
      available: this.data.details.available,
      price: this.data.details.minSalePrice,
      specInfo: this.data.details.specList?.map((item) => ({
        specTitle: item.title,
        specValue: item.specValueList[0].specValue,
      })),
      primaryImage: this.data.details.primaryImage,
      spuId: this.data.details.spuId,
      thumb: this.data.details.primaryImage,
      title: this.data.details.title,
    };
    let urlQueryStr = obj2Params({
      goodsRequestList: JSON.stringify([query]),
    });
    urlQueryStr = urlQueryStr ? `?${urlQueryStr}` : '';
    const path = `/pages/order/order-confirm/index${urlQueryStr}`;
    wx.navigateTo({
      url: path,
    });
  },

  specsConfirm() {
    const {
      buyType
    } = this.data;
    if (buyType === 1) {
      this.gotoBuy();
    } else {
      this.addCart();
    }
    // this.handlePopupHide();
  },

  changeNum(e) {

    this.setData({
      buyNum: e.detail.buyNum,
    });
    // console.log("changeNum", e.detail.buyNum, this.data.buyNum);
  },

  closePromotionPopup() {
    this.setData({
      isShowPromotionPop: false,
    });
  },

  promotionChange(e) {
    const {
      index
    } = e.detail;
    wx.navigateTo({
      url: `/pages/promotion-detail/index?promotion_id=${index}`,
    });
  },

  showPromotionPopup() {
    this.setData({
      isShowPromotionPop: true,
    });
  },

  getDetail(spuId) {
    console.log('getDetail', spuId);
    this.request({
      url: this.data.host + '/v1/goods/' + spuId,
    }, res => {
      // console.log('商品详情', res);

      if (res.data.goodsImages && res.data.goodsImages.length > 0) {
        res.data.goodsImages.map(val => {
          val.value = this.get_imgUrl(val.imgUrl, 750);

        })
        this.setData({
          specImg: res.data.goodsImages[0].value
        })
      }
      // res.data.goodsDetails.map(val => {
      //   val.url = this.get_imgUrl(val.goodsDesc, 750)
      // })
      let labelArr = [];
      res.data.goodsLabels.map(val => {
        val.members.map(val1 => {
          labelArr.push(val1.valueName)
        })

      })
      res.data.labels = labelArr.join("/")
      this.setData({
        details: res.data,
        price: res.data.price
      })
    })
    // Promise.all([fetchGood(spuId), fetchActivityList()]).then((res) => {
    //   console.log('fetchGood(spuId)', res);
    //   const [details, activityList] = res;
    //   const skuArray = [];
    //   const {
    //     skuList,
    //     primaryImage,
    //     isPutOnSale,
    //     minSalePrice,
    //     maxSalePrice,
    //     maxLinePrice,
    //     soldNum,
    //   } = details;
    //   skuList.forEach((item) => {
    //     skuArray.push({
    //       skuId: item.skuId,
    //       quantity: item.stockInfo ? item.stockInfo.stockQuantity : 0,
    //       specInfo: item.specInfo,
    //     });
    //   });
    //   const promotionArray = [];
    //   activityList.forEach((item) => {
    //     promotionArray.push({
    //       tag: item.promotionSubCode === 'MYJ' ? '满减' : '满折',
    //       label: '满100元减99.9元',
    //     });
    //   });
    //   this.setData({
    //     details,
    //     activityList,
    //     isStock: details.spuStockQuantity > 0,
    //     maxSalePrice: maxSalePrice ? parseInt(maxSalePrice) : 0,
    //     maxLinePrice: maxLinePrice ? parseInt(maxLinePrice) : 0,
    //     minSalePrice: minSalePrice ? parseInt(minSalePrice) : 0,
    //     list: promotionArray,
    //     skuArray: skuArray,
    //     primaryImage,
    //     soldout: isPutOnSale === 0,
    //     soldNum,
    //   });
    // });
  },



  onShareAppMessage() {
    // 自定义的返回信息
    const {
      selectedAttrStr
    } = this.data;
    let shareSubTitle = '';
    if (selectedAttrStr.indexOf('件') > -1) {
      const count = selectedAttrStr.indexOf('件');
      shareSubTitle = selectedAttrStr.slice(count + 1, selectedAttrStr.length);
    }
    const customInfo = {
      imageUrl: this.data.details.primaryImage,
      title: this.data.details.title + shareSubTitle,
      path: `/pages/goods/details/index?spuId=${this.data.spuId}`,
    };
    return customInfo;
  },





  onLoad(query) {
    console.log('onLoad', query);
    const spuId = query.sid;
    this.setData({
      spuId: spuId,
      storeSid: query.storeSid || ''
    });
    this.getDetail(spuId);


  },
});